package com.kalix.mplive.answeringQuestion.servlet;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 功能描述:
 *
 * @Description: java类作用描述
 * @Author: yyp
 * @CreateDate: 2019/11/15$ 16:35$
 * @Version:
 */
public class VideoServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            String filePath = request.getParameter("file");
            String strname = filePath.substring(filePath.lastIndexOf("/") + 1);
//            String fname = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + URLEncoder.encode(srtname, "utf-8");

            DefaultHttpClient httpClient = new DefaultHttpClient();
            URL u = new URL(filePath);
            HttpGet httpGet = new HttpGet(filePath);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            InputStream inStream = entity.getContent();

//            File f = new File(filePath);
//            if (!f.exists()) {
//                response.sendError(404, "File not found!");
//                return;
//            }
//            BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
            BufferedInputStream br = new BufferedInputStream(inStream);
            byte[] bs = new byte[1024];
            int len = 0;
            response.reset(); // 非常重要
            response.setContentType("application/x-msdownload");
//            response.setHeader("Content-Disposition", "attachment;filename=" + srtname);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(strname, "UTF-8"));
            OutputStream out = response.getOutputStream();
            while ((len = br.read(bs)) > 0) {
                out.write(bs, 0, len);
            }
            out.flush();
            out.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
}
